﻿using FreeSql;
using Newtonsoft.Json;

namespace duqin.Common
{
    public class PageResult<T> where T : class, new()
    {
        [JsonProperty("total")]
        public long TotalCount { get; set; }

        [JsonProperty("per_page")]
        public int PageSize { get; set; }

        [JsonProperty("current_page")]
        public int PageIndex { get; set; }

        [JsonProperty("last_page")]
        public long TotalPage { get; set; }

        [JsonProperty("data")]
        public IEnumerable<T>? PageData { get; set; }
    }

    public static class PageResultExtension
    {
        public static async Task<PageResult<T>> ToPageAsync<T>(this ISelect<T> query, int page, int limit) where T : class, new()
        {
            var pageResult = new PageResult<T>
            {
                PageIndex = page,
                PageSize = limit
            };

            var data = await query.Count(out var totalCount).Page(page, limit).ToListAsync();
            pageResult.TotalCount = totalCount;

            pageResult.PageData = data;

            pageResult.TotalPage = (totalCount + limit - 1) / limit;

            return pageResult;
        }
    }
}
